/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.irdstudio.apicenter.gateway.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.irdstudio.apicenter.gateway.comm.tcp.MaccsSocketClient;

/**
 * This is an example program demonstrating how to use the FTPClient class. This
 * program connects to an FTP server and retrieves the specified file. If the -s
 * flag is used, it stores the local file at the FTP server. Just so you can see
 * what's happening, all reply strings are printed. If the -b flag is used, a
 * binary transfer is assumed (default is ASCII). See below for further options.
 */
public final class UploadFTPClient {

	public static final String USAGE = "Usage: ftp [options] <hostname> <username> <password> [<remote file> [<local file>]]\n"
			+ "\nDefault behavior is to download a file and use ASCII transfer mode.\n"
			+ "\t-a - use local active mode (default is local passive)\n"
			+ "\t-A - anonymous login (omit username and password parameters)\n" + "\t-b - use binary transfer mode\n"
			+ "\t-c cmd - issue arbitrary command (remote is used as a parameter if provided) \n"
			+ "\t-d - list directory details using MLSD (remote is used as the pathname if provided)\n"
			+ "\t-e - use EPSV with IPv4 (default false)\n"
			+ "\t-f - issue FEAT command (remote and local files are ignored)\n"
			+ "\t-h - list hidden files (applies to -l and -n only)\n"
			+ "\t-k secs - use keep-alive timer (setControlKeepAliveTimeout)\n"
			+ "\t-l - list files using LIST (remote is used as the pathname if provided)\n"
			+ "\t     Files are listed twice: first in raw mode, then as the formatted parsed data.\n"
			+ "\t-L - use lenient future dates (server dates may be up to 1 day into future)\n"
			+ "\t-n - list file names using NLST (remote is used as the pathname if provided)\n"
			+ "\t-p true|false|protocol[,true|false] - use FTPSClient with the specified protocol and/or isImplicit setting\n"
			+ "\t-s - store file on server (upload)\n"
			+ "\t-t - list file details using MLST (remote is used as the pathname if provided)\n"
			+ "\t-w msec - wait time for keep-alive reply (setControlKeepAliveReplyTimeout)\n"
			+ "\t-T  all|valid|none - use one of the built-in TrustManager implementations (none = JVM default)\n"
			+ "\t-PrH server[:port] - HTTP Proxy host and optional port[80] \n"
			+ "\t-PrU user - HTTP Proxy server username\n" + "\t-PrP password - HTTP Proxy server password\n"
			+ "\t-# - add hash display during transfers\n";

	private FTPClient ftp;
	private final static Logger logger = LoggerFactory.getLogger(MaccsSocketClient.class);

	/**
	 * Description: 向FTP服务器上传文件
	 * 
	 * @Version 1.0
	 * @param url
	 *            FTP服务器hostname
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param path
	 *            FTP服务器保存目录
	 * @param filename
	 *            上传到FTP服务器上的文件名
	 * @param input
	 *            输入流
	 * @return 成功返回true，否则返回false *
	 */
	public static boolean uploadFile(String url, // FTP服务器hostname
			int port, // FTP服务器端口
			String username, // FTP登录账号
			String password, // FTP登录密码
			String path, // FTP服务器保存目录
			String filename, // 上传到FTP服务器上的文件名
			InputStream input // 输入流
	) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		ftp.setControlEncoding("GBK");
		try {
			int reply;
			ftp.connect(url, port);// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			//切换目录,如果目录不存在，则创建目录
			boolean allPathSuccess=ftp.changeWorkingDirectory(path);
			System.out.println("目录是否存在："+allPathSuccess);
			if(!allPathSuccess){
				//切换成功不需要创建目录
				mkdirs(ftp, path);
			}
			
			/*
			 * boolean hhe = ftp.makeDirectory(path);
			 * System.out.println("hhe+++++++" + hhe); boolean h2 =
			 * ftp.changeWorkingDirectory(path); System.out.println("h2+++++++"
			 * + h2);
			 */
			ftp.enterLocalPassiveMode();
			boolean tt = ftp.storeFile(filename, input);
			System.out.println("tt" + tt);
			input.close();
			ftp.logout();
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
			return success;
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}
    /**
     * 创建目录方法
     * @param ftpClient 
     * @param dir 写的目录
     * @throws IOException
     */
	public static void mkdirs(FTPClient ftpClient, String dir) throws IOException {
		dir = dir.replace("//", "/");
		String[] dir2 = dir.split("/");
		for (int i = 0; i < dir2.length; i++) {
			dir = dir2[i];
			if (null == dir || "".equals(dir)) {
				continue;
			} else {
				ftpClient.makeDirectory(dir);
				ftpClient.changeWorkingDirectory(dir);
			}
		}

	}

	/**
	 * @deprecated将本地文件上传到FTP服务器上 *
	 * @param url
	 *            服务器hostname
	 * @param port
	 *            服务器端口
	 * @param username
	 *            FTP登陆名
	 * @param password
	 *            FT登陆密码
	 * @param path
	 *            FTP 服务器保存目录
	 * @param filename
	 *            服务器保存文件名
	 * @param orginfilename
	 *            上传文件路径
	 */
	public boolean upLoadFromProduction(String url, // FTP服务器hostname
			int port, // FTP服务器端口
			String username, // FTP登录账号
			String password, // FTP登录密码
			String path, // FTP服务器保存目录
			ArrayList<File> files // 上传到FTP服务器上的文件名
	) {
		boolean flag = false;
		FileInputStream in =null;
		try {
			for (File file : files) {
				in = new FileInputStream(file);
				flag = uploadFile(url, port, username, password, path, file.getName(), in);
				System.out.println(flag);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if (in != null) {
					in.close();
					in = null;
				}
			} catch (Exception e2) {
			}
		}
		return flag;
	}

}
